package com.shanzmoo.merchant.manage.api.manager.product;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shanzmoo.base.bean.PageRespBase;
import com.shanzmoo.base.bean.SHttpResponse;
import com.shanzmoo.base.util.CollectionUtil;
import com.shanzmoo.core.cache.CurrentUserCache;
import com.shanzmoo.db.module.product.domain.dto.UnitSaveDto;
import com.shanzmoo.db.module.product.domain.query.UnitQueryVO;
import com.shanzmoo.db.module.product.domain.vo.UnitSelectVO;
import com.shanzmoo.db.module.product.domain.vo.UnitVO;
import com.shanzmoo.db.module.product.entity.ProductUnitEntity;
import com.shanzmoo.db.module.product.service.IProductUnitService;
import com.shanzmoo.merchant.manage.api.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品单位manager
 * @author xueqz
 */
@Component
@RequiredArgsConstructor
public class ProductUnitManager {

    @Autowired
    private IProductUnitService productUnitService;

    public SHttpResponse<PageRespBase<UnitVO>> getUnitListPage(UnitQueryVO unitQueryVO) {
        // 开启分页
        Page page = productUnitService.page(unitQueryVO.page(), new QueryWrapper<ProductUnitEntity>()
                .eq("deleted", false));
        List<UnitVO> reList = CollectionUtil.convert(page.getRecords(), UnitVO.class);
        PageRespBase<UnitVO> re = PageRespBase.create(page,reList);
        return SHttpResponse.ok(re);
    }


    public SHttpResponse<Boolean> addUnit(UnitSaveDto unitSaveDto) {
        ProductUnitEntity data = unitSaveDto.convert(ProductUnitEntity.class);
        data.setCreateUser(SecurityUtil.getCurrentUserId());
        Assert.isTrue(productUnitService.save(data),"创建商品单位失败");
        return SHttpResponse.ok();
    }

    public SHttpResponse<Boolean> delBrandById(Integer unitId) {
        ProductUnitEntity data = new ProductUnitEntity();
        data.setId(unitId);
        data.setDeleted(Boolean.TRUE);
        data.setUpdateUser(SecurityUtil.getCurrentUserId());
        Assert.isTrue(productUnitService.updateById(data),"更新商品单位失败");
        return SHttpResponse.ok();
    }

    public SHttpResponse<List<UnitSelectVO>> selectList() {
        List<ProductUnitEntity> entityList = productUnitService.list(
                new QueryWrapper<ProductUnitEntity>()
                        .eq("deleted", false)
        );
        List<UnitSelectVO> voList = entityList.stream()
                .map(UnitSelectVO::create)
                .collect(Collectors.toList());
        return SHttpResponse.ok(voList);
    }
}
